import java.util.*;

public class AnagramsSearcher {

    public List<ParsedWord> parseWords(List<String> words) {
        if (words == null)
            return Collections.emptyList();

        List<ParsedWord> result = new ArrayList<ParsedWord>();
        for (String word : words) {
            if (word != null)
                result.add(new ParsedWord(word));
        }
        return result;
    }

    public List<Set<String>> groupsOfAnagrams(List<String> words) {
        if (words == null || words.size() == 0)
            return Collections.emptyList();

        List<ParsedWord> list = parseWords(words);
        Collections.sort(list, new ParsedWordsComparator());

        List<Set<String>> result = new ArrayList<Set<String>>();

        int setIndex = 0;
        result.add(new HashSet<String>());
        result.get(setIndex).add(list.get(0).getWord());

        for (int index = 1; index < list.size(); index++) {
            if (list.get(index).getSignature().equals(list.get(index - 1).getSignature())) {
                result.get(setIndex).add(list.get(index).getWord());
            } else {
                result.add(new HashSet<String>());
                setIndex++;
                result.get(setIndex).add(list.get(index).getWord());
            }
        }
        return result;
    }
}